package com.pelli.imarket.client.panels.listeners;

import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.pelli.imarket.client.GridService;
import com.pelli.imarket.client.GridServiceAsync;
import com.pelli.imarket.client.Imarket;
import com.pelli.imarket.client.panels.HomePanel;
import com.pelli.imarket.client.panels.LoginPanel;

public class LoginListener extends SelectionListener<ButtonEvent> {

	private LoginPanel loginPanel;

	public LoginListener(LoginPanel loginPanel) {
		this.loginPanel=loginPanel;
	}

	private final native String evalJson(String json) /*-{
		alert(json);
		eval('var res = '+json);
		alert(res);
		return res;
	}-*/;
	
	
	@Override
	public void handleEvent(ButtonEvent e) {
		//TODO gestione del Login
		GridServiceAsync gridServiceAsync = GWT.create(GridService.class );
		gridServiceAsync.getData(loginPanel.getTxtUsername().getValue(),loginPanel.getTxtPassword().getValue(), new AsyncCallback<String>() {
			
			@Override
			public void onSuccess(String result) {
				try {
//					System.out.println(evalJson(result.trim()));
					
//					result = "{\"idUser\":\"aghy3UI89qolL82uJJhb\",\"login\":\"edo\",\"password\":\"edo\",\"lista\": []}";
					JSONObject jsonObject = (JSONObject) JSONParser.parseLenient(result.trim());
					System.out.println(jsonObject.get("idUser").isString().stringValue());
					Imarket.getRootPanel().clear();
					Imarket.getRootPanel().add(new HomePanel());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				caught.printStackTrace();
				Window.alert(caught.toString());
				System.out
						.println("LoginListener.handleEvent(...).new AsyncCallback() {...}.onFailure()");
			}
		});
	}

	@Override
	public void componentSelected(ButtonEvent ce) {
		System.out.println("LoginListener.componentSelected()");
	}

}
